# -*- coding: utf-8 -*-
import os, sys, argparse, re
from datetime import datetime
import matplotlib.pyplot as plt


class ReFile:
    def goRe(self, inStr, debug=True):
        if debug:
            print("goRe\ninStr:",inStr.rstrip('\n'))
        
        frameSum = re.search("framesum:\d*", inStr)
        if frameSum == None:
            return False
        frameSum = int(frameSum.group(0)[9:])
        if debug:
            print("frameSum:",frameSum)

        time = re.search("\d\d:\d\d:\d\d\.\d\d\d", inStr)
        time = datetime.strptime(time.group(0), "%H:%M:%S.%f")
        if debug:
            print("time:",time)

        willReturn = {'sum':frameSum, 'time':time}
        if debug:
            print("willReturn:",willReturn)

        return willReturn

    def __init__(self, config) -> None:
        self.targetFile = config.targetFile
        self.outPath    = config.outPath
        self.verbose    = config.verbose
        self.onlySave   = config.onlySave
        self.fileName   = os.path.splitext(os.path.basename(self.targetFile))[0] # 路径中筛选文件名，再去掉后缀

        f = open(self.targetFile, 'r', encoding='utf-8')
        line = f.readline()
        self.frameList = []
        while line:
            if ' D ' not in line:
                line = f.readline()
                continue
            result = self.goRe(line.rstrip('\n'), self.verbose)
            if result != False:
                if result["sum"] == 0 and len(self.frameList) > 2:
                    break
                self.frameList.append(result)

            line = f.readline()

        f.close()

        self.frameLen = len(self.frameList)
        assert (self.frameLen % 2) == 0 , "匹配结果要为双数"
        self.frameLen = int(self.frameLen/2)
        self.s2eDiffList = []
        self.s2sDiffList = [0, ]
        for i in range(self.frameLen):
            assert self.frameList[i*2]['sum'] == i, "索引值要与frameSum相等"+str(self.frameList[i*2]['sum'])+" != "+str(i)
            assert self.frameList[i*2]['sum'] == self.frameList[i*2+1]['sum'], "相邻两行解析的frameSum要相等"+str(self.frameList[i*2]['sum'])+" != "+str(self.frameList[i*2+1]['sum'])
            s2eDiff = self.frameList[i*2+1]['time'] - self.frameList[i*2]['time']
            s2eDiff = s2eDiff.seconds + float(s2eDiff.microseconds)/1000000
            self.s2eDiffList.append(s2eDiff)
            if i != 0:
                s2sDiff = self.frameList[i*2]['time'] - self.frameList[(i-1)*2]['time']
                s2sDiff = s2sDiff.seconds + float(s2sDiff.microseconds)/1000000
                self.s2sDiffList.append(s2sDiff)

        self.output()

    def output(self):
        plt.plot(range(len(self.s2eDiffList)), self.s2eDiffList, 'b--', alpha=0.5, linewidth=1, label='s2e')
        plt.plot(range(len(self.s2sDiffList)), self.s2sDiffList, 'r--', alpha=0.5, linewidth=1, label='s2s')
        plt.legend()  #显示上面的label
        plt.title(self.fileName)
        plt.xlabel('frame') #x_label
        plt.ylabel('diffTime')#y_label
        plt.savefig(os.path.join(self.outPath, self.fileName+'.png')) # plt.show() 后实际上已经创建了一个新的空白图片，要在plt.show()前导出图片
        print("保存图片:"+os.path.join(self.outPath, self.fileName+'.png'))
        if not self.onlySave:
            plt.show()


class Config:
    def __init__(self, targetFile, outPath, verbose, onlySave):
        self.targetFile = os.path.abspath(targetFile)
        self.outPath    = outPath
        self.verbose    = verbose
        self.onlySave   = onlySave

        assert os.path.exists(self.targetFile), "File does not exist: "+self.targetFile
        if not os.path.exists(self.outPath):
            os.makedirs(self.outPath)

def parseArgs():
    # __file__同级路径中out文件夹
    default_basePath    = os.path.abspath(os.path.dirname(__file__))
    default_basePath    = os.path.join(default_basePath,"out")

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('--targetFile',
    dest    = 'targetFile',
    default = 'Berry耗时.txt',
    help    = '指定输入文件。')

    parser.add_argument('--outPath',
    dest    = 'outPath',
    default = default_basePath,
    help    = '指定输出文件存放路径。')

    default_verbose = False
    parser.add_argument('--verbose',
    dest    = 'verbose',
    default = default_verbose,
    action  = "store_false" if default_verbose else "store_true",
    help    = '是否打印脚本信息。')

    default_onlySave = False
    parser.add_argument('--onlySave',
    dest    = 'onlySave',
    default = default_onlySave,
    action  = "store_false" if default_onlySave else "store_true",
    help    = '仅将折线图保存至本地，不进行展示')

    args = parser.parse_args()
    if(args.verbose == True):
        parser.print_help()
        print()
    if(args.targetFile == None):
        sys.exit(-1)

    return args

if __name__ == "__main__":
    args    = parseArgs()
    config  = Config(args.targetFile, args.outPath, args.verbose, args.onlySave)

    readF = ReFile(config)


    